﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Navigation;
using MetroGA.Wp8;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace MetroGA.Samples.WindowsPhone8
{
	public partial class App
	{
		public static PhoneApplicationFrame RootFrame { get; private set; }

		public App()
		{
			InitializeComponent();
			InitializePhoneApplication();

			if (Debugger.IsAttached)
			{
				Current.Host.Settings.EnableFrameRateCounter = true;
				PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
			}

			MetroAnalytics.Initialize("UA-35058453-2", applicationVersion: DateTime.Now.ToString("1.MMdd.HHmm"));
			UnhandledException += (sender, e) => MetroAnalytics.Current.TrackException(e.ExceptionObject);
			RootFrame.Navigated += (sender, e) => MetroAnalytics.Current.TrackView(e.Content.GetType());
		}

		#region Phone application initialization

		private bool _phoneApplicationInitialized = false;


		private void InitializePhoneApplication()
		{
			if (_phoneApplicationInitialized)
				return;

			RootFrame = new PhoneApplicationFrame();
			RootFrame.Navigated += CompleteInitializePhoneApplication;
			RootFrame.Navigated += CheckForResetNavigation;

			_phoneApplicationInitialized = true;
		}

		private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
		{
			RootVisual = RootFrame;
			RootFrame.Navigated -= CompleteInitializePhoneApplication;
		}

		private void CheckForResetNavigation(object sender, NavigationEventArgs e)
		{
			if (e.NavigationMode == NavigationMode.Reset)
				RootFrame.Navigated += ClearBackStackAfterReset;
		}

		private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
		{
			RootFrame.Navigated -= ClearBackStackAfterReset;

			if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
				return;

			while (RootFrame.RemoveBackEntry() != null)
			{ }
		}

		#endregion
	}
}